package school.support.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUtils {

    /**
     * 保存文件
     *
     * @param file
     * @param rootPath
     * @return
     */
    public static String saveFile(MultipartFile file, String rootPath) {
        String fileName = getNewName(file.getOriginalFilename());
        File newFile = new File(rootPath  + fileName);
        newFile.getParentFile().mkdirs();
        try {
            newFile.createNewFile();
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("上传文件: " + newFile.getAbsolutePath());
        return "/"  + fileName;
    }

    private static String getNewName(String name) {
        String back = name.substring(("." + name).lastIndexOf("."));
        return UUID.randomUUID() + "." + back;
    }
}
